package utils

import (
	"github.com/kataras/iris/v12"
	"gorm.io/gorm"
	"strconv"
)

// Paginate 分页封装 pageSize为-1时不分页
func Paginate(page int, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page == 0 {
			page = 1
		}
		if pageSize > 500 {
			pageSize = 500
		}
		if pageSize <= 10 && pageSize >= 0 {
			pageSize = 10
		}
		if pageSize == -1 {
			return db
		}
		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

// SetTotal Header设置总条数 X-Total
func SetTotal(ctx iris.Context, total int64) {
	ctx.Header("x-total", strconv.FormatInt(total, 10))
}
